package com.yc.d0303;

import com.google.gson.Gson;
import com.yc.demo.bean.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/login.s")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        Result result = new Result(0, "", null);
        // 验证用户输入的验证码是否正确
        String ucode = req.getParameter("vcode");
        // 获取会话中保存的验证码
        Object vcode = req.getSession().getAttribute("vcode");
        if (vcode.equals(ucode) == false) {
            result.setMsg("验证码输入错误！");
        } else {
            String name = req.getParameter("name");
            String pwd = req.getParameter("pwd");

            // 三个用户
            if(("yc".equals(name) || "zs".equals(name) || "ls".equals(name))&& "123".equals(pwd)){
                result.setCode(1);
                result.setMsg("登录成功");

                // 由于要显示登录事件, 添加时间
                req.getSession().setAttribute("loginedTime", new Date());
                req.getSession().setAttribute("loginedUser", name);


                // 获取登录前访问的页面
                Object requestURI = req.getSession().getAttribute("requestURI");
                // 放到结果对象中
                result.setData(requestURI);
            } else {
                result.setMsg("用户名或密码错误！");
            }
        }

        String json = new Gson().toJson(result);
        resp.getWriter().append(json);
    }
}
